package com.sf.webside.service;

import com.sf.webside.bean.SysRquestBean;
import com.sf.webside.bean.TokenBean;
import com.sf.webside.config.Global;
import com.sf.webside.dao.SysDictDao;
import com.sf.webside.dao.SysUserDao;
import com.sf.webside.entity.SysDictEntity;
import com.sf.webside.entity.SysUserEntity;
import com.sf.webside.vo.SysDictVO;
import com.sf.webside.vo.SysUserVO;
import entity.ResultVO;
import entity.StatusCode;
import org.apache.http.client.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import util.GsonUtils;
import util.MD5Util;
import util.ResultVOUtil;
import util.SecurityUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by tanjing on 2019/2/21.
 */
@Service
public class SysUserService {
    private Logger logger= LoggerFactory.getLogger(SysUserService.class);
    @Resource
    private Global global;
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysDictDao sysDictDao;

    /**
     * 登录
     */
    public ResultVO login(SysRquestBean sysRquestBean){
        logger.info("login start == "+ GsonUtils.getInstance().toJson(sysRquestBean));
        String loginName=sysRquestBean.getLoginName();
        String password=sysRquestBean.getPassword();
        SysUserEntity sysUserEntity=sysUserDao.findByLoginNameAndDelFlag(loginName,"0");
        if(null==sysUserEntity){
            logger.info("login sysUserEntity is null");
            return ResultVOUtil.error(StatusCode.ERROR,"用户不存在");
        }
        boolean validateFlag=SecurityUtils.validatePassword(password,sysUserEntity.getPassword());
        if(!validateFlag){
            logger.info("login validateFlag is "+validateFlag);
            return ResultVOUtil.error(StatusCode.ERROR,"用户密码输入有误");
        }
        //生成token
        TokenBean tokenBean=generaAndSaveToken(sysUserEntity.getId());
        logger.info("login token == "+ GsonUtils.getInstance().toJson(tokenBean));
        SysUserVO userVO=userEntityToVo(sysUserEntity);
        return ResultVOUtil.success(userVO);
    }

    /**
     * 获取字典
     */
    public ResultVO dict(String type){
        List<SysDictEntity> sysDictEntities=sysDictDao.findByTypeAndDelFlagOrderBySortDesc(type,"0");
        ArrayList arrayList=new ArrayList();
        for (SysDictEntity sysDictEntity:sysDictEntities) {
            SysDictVO sysDictVO=new SysDictVO();
            BeanUtils.copyProperties(sysDictEntity,sysDictVO);
            arrayList.add(sysDictVO);
        }
        return ResultVOUtil.success(arrayList);
    }
    /**
     * 生成并保存token
     * @param userId
     * @return
     */
    public TokenBean generaAndSaveToken(String userId){
        //生成
        String uuid= UUID.randomUUID().toString().replace("-","");
        String createDate=DateUtils.formatDate(new Date());
        String token= MD5Util.MD5(userId+createDate+uuid);
        Date tokenCreateDate=new Date();
        TokenBean tokenBean=new TokenBean();
        tokenBean.setToken(token);
        tokenBean.setCreateDate(tokenCreateDate);
        tokenBean.setExpiresIn(Long.valueOf(global.getTokenValidTime()));
        tokenBean.setUserId(userId);
        //保存
        SysUserEntity userInfo = sysUserDao.findByIdAndDelFlag(userId,"0");
        userInfo.setToken(tokenBean.getToken());
        userInfo.setTokenTime(tokenBean.getCreateDate());
        userInfo.setUpdateDate(new Date());
        sysUserDao.save(userInfo);
        return tokenBean;
    }
    /**
     * VO转换
     * @return
     */
    public SysUserVO userEntityToVo(SysUserEntity sysUserEntity){
        SysUserVO userVO=new SysUserVO();
        BeanUtils.copyProperties(sysUserEntity,userVO);
        return userVO;
    }
    /**
     * 校验token
     *
     * @return
     */
    public ResultVO checkoutToken(String token) {
        SysUserEntity sysUserEntity = sysUserDao.findByTokenAndDelFlag(token,"0");
        if(null==sysUserEntity){
            return ResultVOUtil.error(StatusCode.ERROR_TOKEN_THERE_NO, "账号在其他地方登录");
        }
        TokenBean tokenEntity=new TokenBean();
        tokenEntity.setUserId(sysUserEntity.getId());
        tokenEntity.setToken(sysUserEntity.getToken());
        tokenEntity.setCreateDate(sysUserEntity.getTokenTime());
        tokenEntity.setExpiresIn((long)global.getTokenValidTime());
        //toKen是否过期
        Date createDate=sysUserEntity.getTokenTime();
        Date currntDate=new Date();
        Long expiresIn=(long)global.getTokenValidTime();
        long timeDifference=(currntDate.getTime()-createDate.getTime())/1000;
        if(timeDifference>expiresIn) {
            logger.info("checkoutToken token已过期");
            return ResultVOUtil.error(StatusCode.ERROR_TOKEN_OVERDUE, "token已过期");
        }
        return ResultVOUtil.success(tokenEntity);
    }
}

